package com.automannn.atm_back.codegenerate.util;

import org.apache.commons.lang.RandomStringUtils;

import java.io.IOException;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 辅助生成主键或随机数
 * @author chenkh
 * @time 2020/6/27 15:13
 */
public class RandomUtils {
    private static final SimpleDateFormat aj = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    private static final String[] SPACES = new String[]{"0", "00", "0000", "00000000"};
    private static Date ak;
    private static int counter = 0;

    public RandomUtils() {
    }

    public static String a(int length) {
        return RandomStringUtils.randomAlphanumeric(length);
    }

    public static int B() {
        return (new SecureRandom()).nextInt();
    }

    public static String C() {
        return Integer.toHexString(B());
    }

    public static long D() {
        return (new SecureRandom()).nextLong();
    }

    public static String E() {
        return Long.toHexString(D());
    }

    public static String F() {
        return UUID.randomUUID().toString();
    }

    public static String G() {
        Date now = new Date();
        return aj.format(now);
    }

    public static long H() {
        return System.currentTimeMillis();
    }

    public static String I() {
        return Long.toHexString(H());
    }

    public static synchronized String getCounter() {
        Date currentTime = new Date();
        if (currentTime.equals(ak)) {
            ++counter;
        } else {
            ak = currentTime;
            counter = 0;
        }

        return Integer.toHexString(counter);
    }

    public static String c(String source, int length) {
        int spaceLength = length - source.length();

        StringBuilder buf;
        for(buf = new StringBuilder(); spaceLength >= 8; spaceLength -= 8) {
            buf.append(SPACES[3]);
        }

        for(int i = 2; i >= 0; --i) {
            if ((spaceLength & 1 << i) != 0) {
                buf.append(SPACES[i]);
            }
        }

        buf.append(source);
        return buf.toString();
    }

}
